Linq offers to write queries against various data sources including c# code as same capabilities as SQL database. In this example we need to filter customer name with any letter and having orders. For customer name we can use startwith parameter function. Inorder to filter the customers having orders tables should have foreign key relation. It has already relation by the way we can get orders count. Belew example I will show you how to filter the record(s).
I used jQuery datatable for displaying records.
This example I used northwind sample database for more detail about how to download click link button it will show a popup.
Step 1: Create an ado.net entity data model using table customer and orders and generate entity for that.
Step 2: Right click on the "Controllers" folder and add "Home" controller. Copy and paste the following code. Please make sure to include "LinQTutoris.Models" namespace.
using LinQTutoris.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LinQTutoris.Controllers
{
public class HomeController : Controller
{
models db = new models();
public ActionResult Index()
{
var customerOrders = from customer in db.Customers
where customer.ContactName.StartsWith("C") && customer.Orders.Count > 0
orderby customer.ContactName
select customer;
return View(contactOrders);
}
}
}
Step 3: Right click on the "Index" action method in the "HomeController" and add "Index" view. Copy and paste the following code.
@model IEnumerable<LinQTutoris.Models.Customer>
@{
ViewBag.Title = "filter customer name start with C & having order using linq";
}
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<script type="text/javascript">
$(document).ready(function () {
$('#example').DataTable();
});
</script>
<h2>filter customer name start with C& having order using linq</h2>
<table id="example">
<thead>
<tr>
<th>Contact Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
@foreach (var row in Model)
{
<tr>
<td>@row.ContactName</td>
<td>@row.Country</td>
</tr>
}
</tbody> </table>
Output:
Post your comments / questions
Recent Article
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
Related Article